//
//  KAHomeVC.swift
//  kano
//
//  Created by Sophia on 2024/8/19.
//

import UIKit
import CoreLocation
import Flutter
import FSPagerView
import PopupDialog

class KAHomeVC: KABaseVC, UIScrollViewDelegate {
    
    var auditState: KAAuditState?
    var homeInfo: KAHomeInfo?
    var productInfo: KAProductInfo?
    var coupons: [KAHomeCoupon]? = []
    var news: KAHomeNews?
    
    lazy var draggableButton: UIButton = {
        let button = UIButton(type: .system)
        button.setBackgroundImage(UIImage(named: "servicer"), for: .normal)
        button.frame = CGRect(x: var_screenWidth-kscale(36), y: 500, width: kscale(36), height: kscale(28)) // 初始位置
        button.addTarget(self, action: #selector(serviceClick(_:)), for: .touchUpInside)
        return button
    }()
    
    @objc func serviceClick(_ sender: UIButton) {
        sender.preventDoubleTap()
        KAFlutterManager.showFlutterVC(route: "/onlineService", parameter: ["mobile" : KAUserManager.shared.user.mobile, "version" : KAUserManager.ka_appVersion()])
//        KAFlutterManager.showFlutterVC(route: "/onlineSocket", parameter: ["mobile" : KAUserManager.shared.user.mobile])
    }
    
    lazy var var_scrollView: UIScrollView = {
        let var_scrollView = UIScrollView(frame: CGRectMake(0, 0, view.width, UIDevice.ka_noNavHeight))
        var_scrollView.backgroundColor = .colorFFF
        var_scrollView.isScrollEnabled = true
        //        var_scrollView.contentSize = CGSize(width: var_screenWidth, height: var_screenHeight)
        var_scrollView.bounces = true
        var_scrollView.delegate = self
        return var_scrollView
    }()
    
    lazy var var_bgView: UIImageView = {
        let var_bgView = UIImageView(frame: CGRectMake(0, 0, var_screenWidth, kscale(235)))
        var_bgView.image = UIImage(named: "home_header")
        return var_bgView
    }()
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(16)
        var_titleLabel.y = UIDevice.ka_statusBarHeight + kscale(18)
        var_titleLabel.width = var_screenWidth-kscale(32)
        var_titleLabel.height = kscale(23)
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(18), weight: .bold)
        var_titleLabel.textColor = .color323135
        var_titleLabel.text = "LendSafe"
        return var_titleLabel
    }()
    lazy var var_subTitleLabel: UILabel = {
        let var_subTitleLabel = UILabel()
        var_subTitleLabel.x = kscale(16)
        var_subTitleLabel.y = var_titleLabel.bottom
        var_subTitleLabel.width = var_cornerView.width-kscale(32)
        var_subTitleLabel.height = kscale(22)
        var_subTitleLabel.font = UIFont.systemFont(ofSize: kscale(14), weight: .regular)
        var_subTitleLabel.textColor = .color615F67
        var_subTitleLabel.text = "Instant Loans Made Easy"
        return var_subTitleLabel
    }()
    lazy var var_contentView: UIView = {
        let var_contentView = UIView()
        let y = UIDevice.ka_statusBarHeight+kscale(87)
        var_contentView.frame = CGRectMake(0, y,var_screenWidth, UIDevice.ka_noNavHeight-y)
        var_contentView.backgroundColor = .white
        let maskPath = UIBezierPath(roundedRect: var_contentView.bounds,
                                    byRoundingCorners: [.topLeft, .topRight],
                                    cornerRadii: CGSize(width: 24, height: 24))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = var_contentView.bounds
        maskLayer.path = maskPath.cgPath
        var_contentView.layer.mask = maskLayer
        return var_contentView
    }()
    
    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.layer.borderWidth = 1
        var_cornerView.layer.borderColor = UIColor.colorF4F4FD.cgColor
        var_cornerView.frame = CGRectMake(kscale(16), kscale(16), var_screenWidth-kscale(32), kscale(244))
        return var_cornerView
    }()
    
    lazy var var_tipView: KAHomeTipView = {
        let var_tipView = KAHomeTipView()
        return var_tipView
    }()
    
    lazy var var_creditLabel: UILabel = {
        let var_creditLabel = UILabel()
        var_creditLabel.x = kscale(16)
        var_creditLabel.y = var_tipView.bottom + kscale(16)
        var_creditLabel.width = var_cornerView.width-kscale(32)
        var_creditLabel.height = kscale(22)
        var_creditLabel.font = UIFont.systemFont(ofSize: kscale(14), weight: .regular)
        var_creditLabel.textColor = .color8A8891
        var_creditLabel.text = "Maximum Credit Limit (₦)"
        return var_creditLabel
    }()
    lazy var var_cashImg: UIImageView = {
        let var_cashImg = UIImageView(frame: CGRectMake(kscale(16),var_creditLabel.bottom+kscale(14), kscale(24), kscale(24)))
        var_cashImg.image = UIImage(named: "home_cash_symbol")
        return var_cashImg
    }()
    lazy var var_moneyLabel: UILabel = {
        let var_moneyLabel = UILabel()
        var_moneyLabel.x = kscale(8) + var_cashImg.right
        var_moneyLabel.y = var_creditLabel.bottom
        var_moneyLabel.width = var_cornerView.width-kscale(64)
        var_moneyLabel.height = kscale(52)
        var_moneyLabel.font = UIFont.systemFont(ofSize: kscale(40), weight: .medium)
        var_moneyLabel.textColor = .black
        var_moneyLabel.text = "600,000"
        return var_moneyLabel
    }()
    lazy var var_lineView: UIView = {
        let var_lineView = UIView()
        var_lineView.frame = CGRectMake(0, var_moneyLabel.bottom+kscale(20), var_cornerView.width, 1)
        var_lineView.backgroundColor = .colorF4F4FD
        return var_lineView
    }()
    lazy var var_limitBtn: UIButton = {
        let var_limitBtn = UIButton(frame: CGRectMake(kscale(52), var_lineView.bottom+kscale(14), var_cornerView.width-kscale(104), kscale(50.0)))
        var_limitBtn.setTitle("Get limit", for: .normal)
        var_limitBtn.setTitleColor(.white, for: .normal)
        var_limitBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_limitBtn.backgroundColor = .themeColor
        var_limitBtn.layer.cornerRadius = kscale(25)
        var_limitBtn.layer.masksToBounds = true
        var_limitBtn.addTarget(self, action: #selector(ka_limitButtonClick(_:)), for: .touchUpInside)
        //        var_limitBtn.addTarget(self, action: #selector(showFlutter), for: .touchUpInside)
        
        return var_limitBtn
    }()
    
    var bannerModel: KAHomeBanner?
    lazy var var_banner: FSPagerView = {
        let pagerView = FSPagerView(frame: CGRectMake(kscale(16),var_cornerView.bottom+kscale(10),var_screenWidth - kscale(32), kscale(110)))
        pagerView.dataSource = self
        pagerView.delegate = self
        pagerView.automaticSlidingInterval =  3
        pagerView.isInfinite = false
        pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        pagerView.layer.cornerRadius = kscale(16)
        pagerView.layer.masksToBounds = true
        return pagerView
    }()
    
    var pageControl: FSPageControl {
        let pageControl = FSPageControl(frame: CGRectMake(0, kscale(85), var_screenWidth - kscale(32), kscale(25)))
        pageControl.contentHorizontalAlignment = .center
        pageControl.numberOfPages = bannerModel?.topImageList?.count ?? 0
        return pageControl
    }
    
    lazy var var_overdueView: KAHomeOverdueView = {
        let var_overdueView = KAHomeOverdueView(frame: CGRectMake(kscale(16), var_banner.bottom + kscale(10), var_screenWidth - kscale(32), kscale(152)))
        var_overdueView.isHidden = true
        var_overdueView.repayHandler = {
            let loan = self.homeInfo?.loanBillList?.first
            KAFlutterManager.showFlutterVC(route: "/repayment?loanGid=\(loan!.recordLoanGid)", parameter: [:])
        }
        
        let var_tap = UITapGestureRecognizer(target: self, action: #selector(tapClick(_ :)))
        var_overdueView.addGestureRecognizer(var_tap)
        
        return var_overdueView
    }()
    
    @objc func tapClick(_ sender: UITapGestureRecognizer) {
        let loan = self.homeInfo?.loanBillList?.first
        let vc = KABillDetailVC(with: loan!.recordLoanGid)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func ka_showNotifacation() {
        let center = UNUserNotificationCenter.current()
        
        let content = UNMutableNotificationContent()
        content.title = "Hello"
        content.body = "This is a test notification."
        content.sound = .default
        
        // Create a trigger for the notification (e.g., after 5 seconds)
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        
        // Create the notification request
        let request = UNNotificationRequest(identifier: "TestNotification", content: content, trigger: trigger)
        
        // Schedule the notification
        center.add(request) { error in
            if let error = error {
                // Handle the error
                print("Error scheduling notification: \(error.localizedDescription)")
            }
        }
    }
}

//MARK: - UI
extension KAHomeVC {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //退出授信后清空计数
        KAAdvance.shared.retryCount = 0
        ka_requestHomeInfo()
        ka_requestHomeBanner()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.ka_setUI()
    }
    
    func ka_setUI() {
        view.backgroundColor = .white
        view.addSubview(var_scrollView)
        var_scrollView.addSubview(var_bgView)
        var_scrollView.addSubview(var_contentView)
        var_bgView.addSubview(var_titleLabel)
        var_bgView.addSubview(var_subTitleLabel)
        var_contentView.addSubview(var_cornerView)
        var_contentView.addSubview(var_banner)
        var_contentView.addSubview(var_overdueView)
        
        var_cornerView.addSubview(var_tipView)
        var_cornerView.addSubview(var_creditLabel)
        var_cornerView.addSubview(var_cashImg)
        var_cornerView.addSubview(var_moneyLabel)
        var_cornerView.addSubview(var_lineView)
        var_cornerView.addSubview(var_limitBtn)
        
        view.addSubview(draggableButton)
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
        draggableButton.addGestureRecognizer(panGesture)
        
        let status = CLLocationManager.authorizationStatus()
        if status == .notDetermined || status == .denied{
            KALocationManager.shared.showAlert()
        }
        checkNotificationAuthorization()
    }
    
    // 处理拖动手势
    @objc func handlePanGesture(_ sender: UIPanGestureRecognizer) {
        // 获取拖动手势的偏移量（相对于按钮的初始位置）
        let translation = sender.translation(in: view)
        
        // 只更新按钮的 y 位置，保持 x 不变
        if let button = sender.view {
            let newY = button.center.y + translation.y
            button.center = CGPoint(x: button.center.x, y: newY)
        }
        
        // 重置手势的偏移量
        sender.setTranslation(.zero, in: view)
        
        // 如果手势结束，可以根据需要执行进一步操作
        if sender.state == .ended {
            print("Button moved to vertical position: \(sender.view?.center.y ?? 0)")
        }
    }
    
    func checkNotificationAuthorization() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            switch settings.authorizationStatus {
            case .notDetermined:
                // Permission not yet requested
                break
            case .denied:
                // Permission denied; prompt user to open settings
                DispatchQueue.main.async {
                    self.showSettingsAlert()
                }
            case .authorized, .provisional, .ephemeral:
                // Permission granted
                break
            @unknown default:
                break
            }
        }
    }
    
    func showSettingsAlert() {
        let alert = UIAlertController(
            title: "Notifications Disabled",
            message: "Please enable notifications in the app settings to receive updates.",
            preferredStyle: .alert
        )
        let settingsAction = UIAlertAction(title: "Open Settings", style: .default) { _ in
            if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsUrl)
            }
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alert.addAction(settingsAction)
        alert.addAction(cancelAction)
        
        if let viewController = UIApplication.shared.keyWindow?.rootViewController {
            viewController.present(alert, animated: true, completion: nil)
        }
    }
}

//MARK: - net
extension KAHomeVC {
    
    @objc func ka_limitButtonClick(_ sender: UIButton) {
        sender.preventDoubleTap()
        toBorrow()
    }
    
    func toBorrow(_ couponId: String = "") {
        //        let hasOverdue = homeInfo?.loanBillList?.sorted {$0. > $1}
        //是否已授信 && 授信额度!=0
        if auditState?.auditState == 1 && productInfo?.creditLine != 0  {
            //可借额度 小于 最小借款金额，提示额度不足
            if productInfo!.canBorrowAmount < (productInfo!.productInfoList?.first?.minLoanAmount)! {
                let subTitle = "Your borrowing limit is insufficient and you need to reach ₦Naira to borrow normally"
                let replacedString = subTitle.replacingOccurrences(of: "Naira", with: "\(productInfo?.productInfoList?.first?.minLoanAmount ?? 0)")
                let alert = KAAlertView.alert(withTitle: "", subtitle: replacedString) { _ in
                }
                alert.addAction(KAAlertAction(title: "Confirm", titleColor: .blue, backgroundColor: .clear) { action in
                    
                })
                alert.show()
            }
            //是否有逾期账单，有提示去还款
            else if homeInfo?.loanBillList?.contains(where: { $0.exceedDays > 0 }) == true {
                view.makeToast("You have overdue loan, please apply loan after repay")
            }
            //去借款
            else {
                applyAuto(couponId)
            }
        } else {
            applyAuto(couponId)
        }
    }
    func applyAuto(_ couponId: String = "") {
        guard homeInfo != nil else {
            ka_requestHomeInfo()
            return
        }
        NetService.applyAuto(borrowingLoanType: homeInfo!.borrowingLoanType, couponId) { isSuccess, message, response in
            
        }
    }
    
    func ka_requestHomeInfo() {
        UIViewController.ka_window().showLoading()
        let dispatchGroup = DispatchGroup()
        
        dispatchGroup.enter()
        NetService.ka_requestHomeInfo { [self] isSuccess, message, response in
            if isSuccess {
                guard let content = response?.content else { return }
                homeInfo = content
                
                if (content.firstAuthFlag == 1) {
                    //用户首次授信成功
                    KAAFTool.logEvent(event: "SKP_Firstsuccessfulcredit_extension")
                }
                if (content.firstGetQuotaFlag == 1) {
                    //首次获取额度成功
                    KAAFTool.logEvent(event: "SKP_Successfullyobtained_creditfirst")
                }
                productInfo = NetService.getActiveProduct(content: content)
            } else {
                self.view.makeToast(message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        NetService.ka_requestHomeStatus { [self] isSuccess, message, response in
            if isSuccess {
                guard let content = response?.content else { return }
                auditState = content
            } else {
                self.view.makeToast(message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        let paramDic = [ "userGid":KAUserManager.shared.user.userGid]
        loginProvider.request(.homeNews(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAHomeNews>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            news = content
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        let paraDic = [ "userGid":KAUserManager.shared.user.userGid]
        loginProvider.request(.homeCoupon(paraDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<[KAHomeCoupon]>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            coupons = content
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.notify(queue: .main) {
            UIViewController.ka_window().hideLoading()
            
            //borrowingLoanType: 0:无在借订单  1:短贷  2:大额分期（蝌蚪贷属于小额，这里不影响）
            guard self.homeInfo != nil else {return}
            if self.homeInfo!.borrowingLoanType == 0 {
                // 仅有小额 显示小额；仅有大额，显示大额，大小额都有，看最大可借
                //是否已授信 && 授信额度!=0
                if self.auditState?.auditState == 1 && self.productInfo?.creditLine != 0  {
                    self.var_moneyLabel.text = self.productInfo!.creditLine.separatorString()
                    self.var_creditLabel.text = "Available limit (₦)"
                    self.var_limitBtn.setTitle("Apply now", for: .normal)
                }
                
            } else if self.homeInfo!.borrowingLoanType == 1 {
                // 显示小额的
                var normalLoan: KAProductInfo?
                _ = self.homeInfo!.productInfosList!.map {
                    // 小额
                    if ($0.productType == 1) {
                        normalLoan = $0;
                    }
                }
                self.var_moneyLabel.text = normalLoan!.canBorrowAmount.separatorString()
                self.var_creditLabel.text = "Available limit (₦)"
                self.var_limitBtn.setTitle("Apply now", for: .normal)
            } else if self.homeInfo!.borrowingLoanType == 2 {
                // 显示大额的
                var largeLoan: KAProductInfo?
                _ = self.homeInfo!.productInfosList!.map {
                    // 大额
                    if ($0.productType == 2) {
                        largeLoan = $0;
                    }
                }
                self.var_moneyLabel.text = largeLoan!.canBorrowAmount.separatorString()
                self.var_creditLabel.text = "Available limit (₦)"
                self.var_limitBtn.setTitle("Apply now", for: .normal)
            }
            
            //有3天到期贷款 或 已逾期贷款
            if self.homeInfo?.loanBillList?.count ?? 0 > 0 {
                //返回账单中过期时间最长的账单
                self.homeInfo?.loanBillList?.sort {$0.exceedDays > $1.exceedDays}
                self.var_overdueView.isHidden = false
                self.var_overdueView.model = self.homeInfo?.loanBillList?.first
            } else {
                self.var_overdueView.isHidden = true
            }
            
            //营销公告
            if self.news?.marketActivities?.count ?? 0 > 0 {
                for item in self.news!.marketActivities! {
                    self.showMarketAlert(newModel: item)
                }
            }
            //普通公告集合
            if self.news?.noticeContent?.count ?? 0 > 0 {
                for item in self.news!.noticeContent! {
                    self.showNormalAlert(newModel: item)
                }
            }
            //优惠券
            if self.coupons?.count ?? 0 > 0 {
                self.showCouponAlert(coupons: self.coupons!)
            }
            //熔断公告
            if self.news?.newsType == 0 && self.news?.noticeContent?.first?.dialogType == 2 {
                self.showUninteractionAlert(newModel: self.news!.noticeContent!.first!)
            }
 
        }
    }
    
    func hasTodayShowed(key: String) -> Bool {
        if let value = UserDefaults.standard.value(forKey: key) as? Date {
            let calendar = Calendar(identifier: .gregorian)
            return calendar.isDateInToday(value) ? true : false
        } else {
            return false
        }
    }
    func hasShowed(key: String) -> Bool {
        if let value = UserDefaults.standard.value(forKey: key) as? Bool {
            return true
        } else {
            return false
        }
    }
    
    func showNormalAlert(newModel: KAHomeNewsContent) {
        //中度公告 在公告使用期间，不管打开多少次该页面，每天只弹出一次该公告
        if newModel.strongWeakType == 2 && hasTodayShowed(key: "\(newModel.id)_\(KAUserManager.shared.user.userGid)") {
            return
        }
        //弱公告 只弹一次
        if newModel.strongWeakType == 3 && hasShowed(key: "\(newModel.id)_\(KAUserManager.shared.user.userGid)") {
            return
        }
        
        let subStr = newModel.content.htmlToAttributedString() ?? NSAttributedString(string: "")
        
        let alert = KAAlertView.alert(withTitle: newModel.title, attributedSubtitle: subStr)
        alert.addAction(KAAlertAction(title: "I know", titleColor: .blue, backgroundColor: .clear))
        alert.showOnWindow()
        
//        let alert = UIAlertController(title: newModel.title, message: nil, preferredStyle: .alert)
//        alert.setValue(subStr, forKey: "attributedMessage")
//        let okAction = UIAlertAction(title: "I know", style: .default)
//        alert.addAction(okAction)
//        if let viewController = UIApplication.shared.keyWindow?.rootViewController {
//            viewController.present(alert, animated: true, completion: nil)
//        }
        
        if newModel.strongWeakType == 2 {
            UserDefaults.standard.set(Date(), forKey: "\(newModel.id)_\(KAUserManager.shared.user.userGid)")
        }
        if newModel.strongWeakType == 3 {
            UserDefaults.standard.set(true, forKey: "\(newModel.id)_\(KAUserManager.shared.user.userGid)")
        }

    }
    
    func showMarketAlert(newModel: KAHomeNewsContent) {
        if newModel.strongWeakType == 2 && hasTodayShowed(key: "\(newModel.id)_\(KAUserManager.shared.user.userGid)") {
            return
        }
        if newModel.strongWeakType == 3 && hasShowed(key: "\(newModel.id)_\(KAUserManager.shared.user.userGid)") {
            return
        }
        let alertView = KAMarketAlertView(model: newModel)
        alertView.handler = { type, model in
            alertView.ka_dismiss()
            if type == 1 {
                if ["/lendInfo", "/risk"].contains(model?.extendUrl) {
                    self.toBorrow()
                }
                if model?.extendUrl == "/bill" {
                    self.navigationController?.pushViewController(KABillListVC(), animated: true)
                }
            }
        }
        alertView.ka_show()
        if newModel.strongWeakType == 2 {
            UserDefaults.standard.set(Date(), forKey: "\(newModel.id)_\(KAUserManager.shared.user.userGid)")
        }
        if newModel.strongWeakType == 3 {
            UserDefaults.standard.set(true, forKey: "\(newModel.id)_\(KAUserManager.shared.user.userGid)")
        }
    }
    
    func showCouponAlert(coupons: [KAHomeCoupon]) {
        if hasTodayShowed(key: "Coupon_\(KAUserManager.shared.user.userGid)") {
            return
        }
        let alertView = KACouponAlertView(title: "My Coupon", subTitle: "Borrow now with your coupon and get discounts on interest rates! Please use it on time", actionTitle: "", listData: coupons)
        alertView.handler = { type, model in
            alertView.ka_dismiss()
            if type == 1 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    KAFlutterManager.showFlutterVC(route: "/voucherList", parameter: ["mobile" : KAUserManager.shared.user.mobile])
                }
            } else if type == 2 {
                self.toBorrow(model!.gid)
            }
        }
        alertView.ka_show()
        UserDefaults.standard.set(Date(), forKey: "Coupon_\(KAUserManager.shared.user.userGid)")
    }
    
    func showUninteractionAlert(newModel: KAHomeNewsContent) {
        let subStr = newModel.content.htmlToAttributedString() ?? NSAttributedString(string: "")
        
        let alert = KAAlertView.alert(withTitle: newModel.title, attributedSubtitle: subStr)
        alert.addAction(KAAlertAction(title: "I know", titleColor: .blue, backgroundColor: .clear))
        alert.showOnWindow()
    }
    
    func ka_requestHomeBanner() {
        view.showLoading()
        let paraDic = [ "userGid":KAUserManager.shared.user.userGid ]
        loginProvider.request(.homeBanner(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAHomeBanner>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            bannerModel = content
                            if bannerModel?.topImageList?.count ?? 0 > 0 {
                                self.pageControl.isHidden = false
                                //pageControl.numberOfPages = bannerModel?.topImageList?.count ?? 0
                                var_banner.addSubview(pageControl)
                                self.var_banner.reloadData()
                            } else {
                                self.pageControl.isHidden = true
                            }
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

//MARK: - banner
extension KAHomeVC: FSPagerViewDataSource, FSPagerViewDelegate {
    public func numberOfItems(in pagerView: FSPagerView) -> Int {
        return bannerModel?.topImageList?.count ?? 1
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.imageView?.clipsToBounds = true
        cell.imageView?.contentMode = .scaleAspectFill
        cell.textLabel?.superview!.isHidden = true
        cell.contentView.layer.shadowColor = UIColor.clear.cgColor
        cell.contentView.layer.shadowRadius = 0
        cell.contentView.layer.shadowOpacity = 0
        cell.contentView.layer.shadowOffset = .zero
        
        if bannerModel?.topImageList?.count ?? 0 > 0 {
            let cellModel = bannerModel?.topImageList![index]
            cell.imageView?.kf.setImage(with: URL(string: cellModel?.imageUrl ?? ""))
        } else {
            cell.imageView?.image = UIImage(named: "home_tip")
        }
        return cell
        
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        if bannerModel?.topImageList?.count ?? 0 > 0 {
            let cellModel = bannerModel?.topImageList![index]
            guard let url = URL(string: cellModel?.targetUrl ?? "") else { return }
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:]) { (success) in
                    if success {
                        print("success open URL: \(cellModel?.targetUrl ?? "")")
                    } else {
                        print("fail open URL")
                    }
                }
            } else {
                print("invalid URL")
            }
        }
    }
    func pagerViewWillEndDragging(_ pagerView: FSPagerView, targetIndex: Int) {
        self.pageControl.currentPage = targetIndex
    }
    
    func pagerViewDidEndScrollAnimation(_ pagerView: FSPagerView) {
        self.pageControl.currentPage = pagerView.currentIndex
    }
}
